{% extends "courses/courses-generic.tpl" %}

{% block title %}Chat Testing 123{% endblock %}

{% block content %}

<style type="text/css">
div#chatbox p{
    margin:0 0 8pt 0;
    padding:0;
    font-family: sans-serif;
    font-size: 11pt;
}
</style>

<script type="text/javascript">
var chatbox, textarea, label, submit, lastId, untilId, posting, polling, gettingOlder, pollingIndicator;

const POLL_TIME = 500;

$(function(){
    chatbox=$('#chatbox');
    textarea=$('textarea');
    label=$('label');
    submit=$('input[type="submit"]');
    pollingIndicator = $('#polling');
    $.getJSON('{{ course.chat.getMessagesUrl }}', {}, function(response){
        if(!response || !response.status){
            $('#loading').text('Oops, sorry, there was a problem loading messages.');
			return;
		}
		$('#loading').remove();
        parseResponse(response);
        untilId = lastId - 9;
        chatbox.scroll(getOlder);
        polling=false;
        //setTimeout(poll, POLL_TIME);
        setInterval(poll, POLL_TIME);
    });
});
function appendMsg(msg){
	var wasAtBottom = (chatbox[0].scrollHeight - chatbox.scrollTop() <= chatbox.outerHeight());
	chatbox.append('<p><b>'+msg.user+':</b> '+msg.content);
	if(wasAtBottom)
		chatbox.scrollTop(chatbox[0].scrollHeight);
}
function poll(){
    if(!polling){
        polling=true;  
        pollingIndicator.show();
        $.getJSON('{{ course.chat.getCachedMessagesUrl }}', {last_id:lastId}, function(response){
            parseResponse(response);
            pollingIndicator.hide();
            //setTimeout(poll, POLL_TIME);
            //this was causing a massive memory leak, i think... 
            //a gajillion instances of $ which never get deleted...
            //switching back to
            //setInterval(poll).
            polling=false;
        });
    }
}

function parseResponse(response){
	lastId=response.last_id;
	for(var i = 0; i < response.messages.length; i += 1)
		appendMsg(response.messages[i]);
}
function postMessage(){
	if(posting)
		return;
	posting=true;
	submit.attr('disabled','disabled');
	label.html('Posting your message...');
	$.post('{{ course.chat.postMessageUrl }}', {'content' : textarea.val()} , function(response) {
	    //alert('OMG! postMessage returned!');
		posting=false;
		if(!response || !response.status){
			alert("Oops, sorry, there was a problem posting your message.");
			label.html('Could not post message');
		}else{
			label.html('&nbsp;');
			textarea.val('');
		}
		submit.removeAttr('disabled');
	}, 'json');
}
function getOlder(){
    if(gettingOlder || chatbox.scrollTop() > 200)
        return;
    gettingOlder=true;
    if(untilId > 1)
    // get one extra to see if there are any more
    $.getJSON('{{ course.chat.getMessagesUrl }}', {last_id:untilId,num_msgs:11}, function(response) {
        untilId -= 10;
        for(var i = 0; i < Math.min(response.messages.length,10); i += 1)
            chatbox.scrollTop(chatbox.scrollTop()+$('<p><b>'+response.messages[i].user+':</b> '+response.messages[i].content+'</p>').prependTo(chatbox).outerHeight(true));
        gettingOlder=false;
        if (response.messages.length <= 10)
            untilId = 0;
    });
}
</script>

<h2><a href="{{course.url}}">{{ course }}</a></h2>

<div id="chatbox" style="height:200px;width:200px;overflow-y:scroll;border:solid black 1pt;padding:2pt">
<p id="loading">Loading...</p>
</div>

<form onsubmit="postMessage();return false">
<label>&nbsp;</label>
<br>
<textarea rows=2 style="width:200px;float:left;font-family:Verdana" onkeydown="if(event.keyCode==13 && !event.shiftKey){postMessage();return false;}"></textarea>
</form>

<p id="polling" style="color:gray;display:none">Polling...</p>

{% endblock content %}
